<template>
    <div class="page" ref="pageRef">
        <AdminLayout
            :left-fixed="true"
            no-sel-message="请选择公司或部门再进行操作~"
            ref="adminLayout"
        >
            <template #left>
                <div class="company-list">
                    <div class="search-box">
                        <img class="logo" src="@/assets/Lw/search.png" alt="" />
                        <a-input-search
                            class="search"
                            placeholder="搜索角色"
                            v-model:value="searchCompany"
                            allowClear
                        />
                    </div>
                    <div class="add-box">
                        <div>部门(7)</div>
                        <PlusOutlined />
                    </div>
                    <DepartmentTree
                        ref="departmentTreeComp"
                        v-model:selectedKeys="selectedCompanyKeys"
                        v-model:expandedKeys="expandedKeys"
                        @select="hdlSelectCompany"
                        :postCompanyListCallBack="postCompanyListCallBack"
                        :orgId="userInfo.orgId"
                        @modifyDepartment="hdlModifyDepartment($event)"
                        @deleteDepartment="hdlDeleteDepartment($event)"
                        :searchCompany="searchCompany"
                    ></DepartmentTree>
                </div>
            </template>
            <template #default="{ userInfo: { beSuperAdmin, orgId } }">
                <div class="page-container">
                    <div class="page-title">
                        <div class="left">
                            <div class="name">
                                党委办公司 (<span>12</span>人)
                                <img src="@/assets/Lw/help.png" alt="" />
                            </div>
                            <SystemBreadcrumb />
                        </div>
                        <div class="search-box">
                            <a-input-search
                                width="460"
                                placeholder="请输入"
                                enter-button
                            />
                        </div>
                    </div>
                    <div
                        class="table-box"
                        :class="{ active: isShowCompanyInfo }"
                    >
                        <div class="title-box">
                            <div class="btns-box">
                                <a-button
                                    type="primary"
                                    @click="hdlAddUser"
                                    :icon="h(PlusOutlined)"
                                    v-if="
                                        authApis.includes(
                                            departmentManageService.SAVEUSER,
                                        )
                                    "
                                >
                                    新建成员
                                </a-button>
                            </div>
                        </div>
                        <a-table
                            :columns="columns"
                            :data-source="lazyTable.data"
                            :pagination="lazyTable.pagination"
                            :loading="lazyTable.loading"
                            @change="handleTableChange"
                            size="small"
                            :row-class-name="
                    (_record:any, index:number) =>
                        index % 2 === 1 ? 'table-striped' : null
                "
                        >
                            <template
                                #bodyCell="{ column, record, text, index }"
                            >
                                <template v-if="column.dataIndex === 'name'">
                                    {{ text }}
                                    <span
                                        class="beDepartHead"
                                        v-show="record.beDepartHead"
                                        >{{
                                            record.beDepartHead ? "负责人" : ""
                                        }}</span
                                    >
                                </template>
                                <template
                                    v-if="column.dataIndex === 'departmentId'"
                                >
                                    {{ getCompanyDepthName(text)?.depthName }}
                                </template>

                                <template v-if="column.dataIndex === 'state'">
                                    <a-button
                                        class="status-btn"
                                        :class="[
                                            text == 0
                                                ? 'status-btn__success'
                                                : 'status-btn__error',
                                        ]"
                                    >
                                        {{ text == 0 ? "正常" : "停用" }}
                                    </a-button>
                                </template>

                                <template v-if="column.dataIndex === 'btns'">
                                    <div class="btns">
                                        <a-button
                                            type="text"
                                            class="text__btn--primary"
                                            @click="hdlModifyUser(record.id)"
                                        >
                                            编辑
                                        </a-button>
                                        <a-divider type="vertical" />
                                        <a-popconfirm
                                            title="删除后不可恢复，请确认是否删除?"
                                            @confirm.stop="remove(record.id)"
                                            class="popconfirm"
                                            :getPopupContainer="
                                                getPopupContainer
                                            "
                                            placement="topLeft"
                                        >
                                            <a-button
                                                type="text"
                                                danger
                                                class="text__btn--primary"
                                            >
                                                删除
                                            </a-button>
                                        </a-popconfirm>
                                    </div>
                                </template>
                            </template>
                        </a-table>
                    </div>
                </div>
            </template>
        </AdminLayout>
    </div>
    <a-modal
        v-model:open="openDeleteDepartment"
        title="确认删除"
        :getContainer="getContainer"
        :width="514"
    >
        <div>删除后不可恢复，请确认删除「公司领导」角色？</div>
    </a-modal>
    <a-modal
        v-model:open="openDepartment"
        title="添加部门"
        :getContainer="getContainer"
    >
        <a-form layout="vertical">
            <a-form-item label="部门名称" name="name">
                <a-input placeholder="请输入" autocomplete="off" />
            </a-form-item>
            <a-form-item label="上级部门" name="name">
                <a-input placeholder="选择" autocomplete="off" />
            </a-form-item>
            <a-form-item label="备注">
                <a-textarea placeholder="请输入" :rows="4" autocomplete="off" />
            </a-form-item>
        </a-form>
    </a-modal>
    <a-modal
        v-model:open="openUser"
        title="添加部门"
        :getContainer="getContainer"
    >
        <a-form layout="vertical">
            <a-form-item label="姓名" name="name">
                <a-input placeholder="请输入" autocomplete="off" />
            </a-form-item>
            <a-form-item label="手机号" name="name">
                <a-input placeholder="选择" autocomplete="off" />
            </a-form-item>
            <a-form-item label="部门">
                <a-input placeholder="选择" autocomplete="off" />
            </a-form-item>
            <a-form-item label="角色">
                <a-input placeholder="选择" autocomplete="off" />
            </a-form-item>
            <a-form-item label="状态">
                <a-radio-group>
                    <a-radio value="1">正常</a-radio>
                    <a-radio value="2">停用</a-radio>
                </a-radio-group>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup lang="ts">
    import { h, nextTick, onMounted, ref, watch } from "vue";
    import departmentManageService from "@/service/departmentManage.service";
    import roleManageService from "@/service/roleManage.service";
    import useGlobalStore from "@/stores/global.store";
    import { storeToRefs } from "pinia";
    import AdminLayout from "@/components/AdminLayout/AdminLayout.vue";
    import DepartmentTree from "@/components/DepartmentTree/DepartmentTree.vue";
    import { useRoute, useRouter } from "vue-router";
    import useComapnyTreeLazyTable from "@/hooks/useComapnyTreeLazyTable";
    import { message } from "ant-design-vue";
    import {
        SearchOutlined,
        UndoOutlined,
        PlusOutlined,
    } from "@ant-design/icons-vue";
    import { RoleInfo } from "@/type/roleManage";
    import SystemBreadcrumb from "@/components/SystemBreadcrumb/SystemBreadcrumb.vue";
    const searchCompany = ref();

    const pageRef = ref();
    const openDeleteDepartment = ref(false);
    const openDepartment = ref(false);
    const openUser = ref(false);

    const adminLayout = ref();
    const departmentTreeComp = ref();

    const router = useRouter();
    const route = useRoute();

    const globalStore = useGlobalStore();
    const { userInfo, authApis } = storeToRefs(globalStore);

    onMounted(() => {
        searchObj.value.wordType = "name";
        getRoles();
        nextTick(() => {
            let columnItem = {
                dataIndex: "btns",
                title: "操作",
                width: "140px",
            };
            if (
                authApis.value.includes(departmentManageService.UPDATEUSER) ||
                authApis.value.includes(departmentManageService.REMOVE)
            ) {
                columns.value.push(columnItem);
            }
        });
    });

    const roles = ref<RoleInfo[]>();
    const getRoles = async () => {
        let res = await roleManageService.getAllRolesByCompany();
        let data = res.data.result.data;
        roles.value = data;
    };

    const selectedCompanyKeys = ref<any[]>([]);
    const expandedKeys = ref<any[]>();

    const selOrgId = ref();
    selOrgId.value = userInfo.value.orgId;

    const selDepartmentId = ref();
    const selIsDepartmentRef = ref<any>();
    const hdlSelectCompany = (selectedKeys: any[], e: any) => {
        //获取现在公司及部门id
        if (selectedKeys.length > 0) {
            let node = e.node;
            let isDepartment = node.isDepartment;
            let selIsDepartment = (selIsDepartmentRef.value = isDepartment);
            if (selIsDepartment) {
                selDepartmentId.value = node.key;
                let departmentId = node.key.replace("x", "");
                searchObj.value["departmentId"] = departmentId;
                searchObj.value["departmentName"] = node.title;
            } else {
                searchObj.value["departmentId"] = "";
                searchObj.value["departmentName"] = "";
                selDepartmentId.value = "";
            }

            while (node && isDepartment && node.parent) {
                let pn = node.parent.node;
                let pp = node.parent.parent;
                if (pn.isDepartment && pp) {
                    node = node.parent;
                    isDepartment = node.node.isDepartment;
                } else {
                    node = node.parent;
                    break;
                }
            }

            searchObj.value["orgId"] = node.key;
            searchObj.value["orgName"] = node.title;
            selOrgId.value = node.key;
            isShowCompanyInfo.value = true;

            hdlResetSearchObj(["wordType"]);
        } else {
            isShowCompanyInfo.value = false;
            selDepartmentId.value = "";
            selOrgId.value = "";
        }
    };
    const hdlAddDepartment = () => {
        console.log(selOrgId.value);
        router.push({
            path: "departmentManageEdit",
            query: {
                orgId: selOrgId.value,
                departmentId: selDepartmentId.value,
            },
        });
    };

    const hdlModifyDepartment = (dataId: string) => {
        if (dataId) {
            router.push({
                path: `departmentManageEdit`,
                query: {
                    orgId: selOrgId.value,
                    departmentId: dataId,
                    type: "MODIFY",
                },
            });
        }
    };
    const otherResetSearchObj = (searchObj: any, cloneSearchValueObj: any) => {
        searchObj.value.state = undefined;
    };
    const {
        isShowCompanyInfo,
        lazyTable,
        searchObj,
        search,
        remove,
        handleTableChange,
        noAdmin,
        initSearchParams,
        hdlChangeStatus,
        dateRange,
        // selectedDays,
        // hdlChangeDateRange,
        // hdlChangeDays,
        hdlSearch,
        hdlResetSearchObj,
        pageLoading,
        getPopupContainer,
        presets,
        filterColums,
        hdlCancelChangeStatus,
    } = useComapnyTreeLazyTable(
        departmentManageService,
        otherResetSearchObj,
        true,
        false,
        null,
    );

    const postCompanyListCallBack = async (orgs: any) => {
        const query = route.query;
        let departmentId = query.departmentId as string;
        let orgId = query.orgId as string;

        selDepartmentId.value = departmentId
            ? departmentId + "x"
            : departmentId;
        selOrgId.value = orgId || userInfo.value.orgId;

        if (departmentId) {
            selectedCompanyKeys.value = [departmentId + "x"];
            expandedKeys.value = [departmentId + "x"];
            isShowCompanyInfo.value = true;
            selIsDepartmentRef.value = true;
        } else if (orgId) {
            selectedCompanyKeys.value = [orgId];
            expandedKeys.value = [orgId];
            isShowCompanyInfo.value = true;
        }
    };

    const hdlDeleteDepartment = async (dataId: string) => {
        if (dataId) {
            try {
                pageLoading.value = true;
                let res = await departmentManageService.deleteDapartment(
                    dataId.replace("x", ""),
                );
                message.success("删除成功");
                isShowCompanyInfo.value = false;
                adminLayout.value.isSelectedCompany = false;
                selectedCompanyKeys.value = [];
                departmentTreeComp.value &&
                    departmentTreeComp.value.getCompanys();
                router.replace({ query: {} });
            } finally {
                pageLoading.value = false;
            }
        }
    };

    const hdlModifyUser = (id: string) => {
        router.push({
            path: `departmentManageEditUserEdit`,
            query: {
                orgId: selOrgId.value || "",
                departmentId: selDepartmentId.value || "",
                id,
            },
        });
    };

    const hdlAddUser = () => {
        router.push({
            path: `departmentManageEditUserEdit`,
            query: {
                orgId: selOrgId.value || "",
                departmentId: selDepartmentId.value || "",
            },
        });
    };
    type DepthInfo = {
        name: string;
        depthName: string;
        key: string;
    };
    let companyDepthNameCache: { [key: string]: DepthInfo } = {};
    const getCompanyDepthName = (key: string) => {
        let list: any[] = departmentTreeComp.value.companyTree
            ? [...departmentTreeComp.value.companyTree]
            : [];
        if (list.length == 0) {
            return null;
        }
        if (companyDepthNameCache[key]) {
            return companyDepthNameCache[key];
        }
        let obj: DepthInfo = { name: "", depthName: "", key: "" };

        // let list = dataSource.value;

        function parse(key: any, tree: any[], path: any[] = []) {
            for (const node of tree) {
                path.push(node.title);
                if (node.key === key) {
                    return path;
                }
                if (node.children.length > 0) {
                    const result: any = parse(key, node.children, path);
                    if (result) {
                        return result;
                    }
                }
                path.pop(); // 如果当前节点不是目标节点，弹出当前节点的 ID
            }
            return null; // 没有找到目标节点，返回 null
        }
        let path: any[] = [];
        parse(key, list, path);

        path = path.slice(1);
        obj.key = key;
        let len = path.length;
        obj.name = path[len - 1];
        obj.depthName = path.join(" / ");
        companyDepthNameCache[key] = obj;

        return obj;
    };

    const columns = ref<any[]>([
        {
            dataIndex: "name",
            title: "姓名",
        },

        {
            dataIndex: "departmentId",
            title: "部门",
        },
        {
            dataIndex: "phone",
            title: "手机号",
        },
        {
            dataIndex: "roleName",
            title: "角色",
        },
        // {
        //     dataIndex: "",
        //     title: "数据权限",
        // },
        // {
        //     dataIndex: "onTheJob",
        //     title: "在职情况",
        // },
        {
            dataIndex: "state",
            title: "状态",
        },
        {
            dataIndex: "btns",
            title: "操作",
            width: "140px",
        },
    ]);

    const getContainer = () => {
        return pageRef.value;
    };
</script>

<style lang="scss" scoped src="./DepartmentManage.scss"></style>
